package com.iot08.api.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.iot08.api.utils.request.ParamHandle;
import com.iot08.api.vo.request.DelDeviceDailyReqVO;
import com.iot08.api.vo.request.GetLocationTOJuHuoReqVO;
import com.iot08.common.constant.Const;
import com.iot08.common.entity.app.DeviceLocationDaily;
import com.iot08.common.entity.app.DeviceMessage;
import com.iot08.common.entity.app.ResetDevice;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.response.ResponseMap;
import com.mongodb.client.FindIterable;
import com.mongodb.client.model.Filters;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @version 1.0
 * @Description:
 * @author: Rock
 * @time: 2021/1/25 15:40
 */
@Slf4j
@Service
public class DeviceLocationDailyService extends BaseService<DeviceLocationDaily> {

    @Resource
    private ResetDeviceService resetDeviceService;
    @Resource
    private DeviceLocationService deviceLocationService;

    /**
     * @param deviceLocationDaily
     * @time: 2021/2/25 17:17
     * @author: Rock
     * @version 1.0
     */
    @Override
    public DeviceLocationDaily save(DeviceLocationDaily deviceLocationDaily) {
        //更新时
        //定位轨迹的失效时间是 7天左右 可调整
        deviceLocationDaily.setExpiryAt(DateUtil.getDevLocExpiryAt());
        return mongoTemplate.save(deviceLocationDaily);
    }

    /**
     * 设备定位数据每日统计
     *
     * @param imei
     * @param vo
     * @time: 2021/2/4 10:14
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap getLocationDailyToJuHuo(String imei, GetLocationTOJuHuoReqVO vo) {
        ResponseMap res = ResponseMap.success();
        Date resetDate = null;
        ResetDevice resetDevice = resetDeviceService.findById(imei);
        if (resetDevice != null && resetDevice.getResetTime() != null) {
            resetDate = DateUtil.addDay(resetDevice.getResetTime(), -1);
        }
        List<Object> daily = new ArrayList<>();
        Document query = new Document();
        query.put("i", imei);
        //参数query处理
        ParamHandle.queryParamHandle(query, vo.getQuery());
        FindIterable<Document> document = this.findDoc(query, Filters.eq("date", -1), vo.getPage(), vo.getNum());
        for (Document doc : document) {
            Map<String, Object> temp = new HashMap<>();
            if (resetDate == null || doc.get("date") instanceof Date
                    && doc.getDate("date").compareTo(resetDate) == 1) {
                temp.put("id", doc.get("_id").toString());
                temp.put("date", DateUtil.dateToStr(doc.getDate("date"), DateUtil.FORMAT_4));
                temp.put("amount", doc.get("sum"));
                daily.add(temp);
            }
        }
        res.put("daily", daily);
        return res;
    }

    /**
     * 删除定位数据每日统计
     *
     * @param imei
     * @param vo
     * @time: 2021/2/4 10:20
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap delLocationDailyToJuHuo(String imei, DelDeviceDailyReqVO vo) {
        JSONArray idArr = JSON.parseArray(vo.getDailyIds());
        for (int i = 0; i < idArr.size(); i++) {
            if (!ObjectId.isValid(idArr.getString(i))) {
                continue;
            }
            ObjectId oid = new ObjectId(idArr.getString(i));
            DeviceLocationDaily daily = this.findById(oid);
            if (daily != null) {
                this.delById(oid);
                //通过日期找出当天所有轨迹点, 并且删除
                if (daily.getDate() != null) {
                    double startTime = daily.getDate().getTime() / 1000;
                    double endTime = startTime + 86400;
                    Criteria criteria = Criteria.where("i").is(imei).andOperator(Criteria.where("t").gte(startTime), Criteria.where("t").lte(endTime));
                    deviceLocationService.delByQuery(new Query(criteria));
                }
            }
        }
        return ResponseMap.success();
    }

}
